<template>
  <div class="out_div">
    <div class="baseList">
      <el-form class="searchForm" ref="userSearchForm" size="small" :model="userSearchForm">
        <el-row :gutter="5">
          <el-col :span="6">
            <el-form-item prop="userName" label="用户名:">
              <el-input clearable placeholder="请输入用户名"
                        v-model="userSearchForm.userName"
                        name="userName"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item prop="name" label="姓名:">
              <el-input clearable placeholder="请输入姓名"
                        v-model="userSearchForm.name"
                        name="name"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item prop="phone" label="手机:">
              <el-input clearable placeholder="请输入手机"
                        v-model="userSearchForm.phone"
                        name="phone"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-button icon="el-icon-search" type="primary" size="mini"
                       @click="searchUserHandler">查询
            </el-button>
            <el-button icon="el-icon-refresh-right" type="info" size="mini"
                       @click="resetUserHandler">重置
            </el-button>
          </el-col>
        </el-row>
      </el-form>
      <toolbar @on-add="addUserHandler" :privileges="btnPrivileges"
               :keys="['add']"/>
      <paginatable :keys="['edit','del']" :privileges="btnPrivileges"
                   v-loading="userTblOpts.loading"
                   @row-edit="editUserHandler"
                   @row-del="delUserHandler"
                   @on-pagination="paginationUserHandler"
                   :tblOpts="userTblOpts"/>
    </div>
    <el-dialog @open="dialogOpenHandler" title="添加/编辑" width="30%"
               :visible.sync="showEditDialog">
      <el-form :rules="editFromRules" v-loading="formLoading" class="editForm" size="small" label-width="90px"
               :model="userEditForm"
               ref="userEditForm">
        <el-form-item class="hidden" prop="id">
          <el-input v-model="userEditForm.id" type="hidden"/>
        </el-form-item>
        <el-row :gutter="5">
          <el-col :span="22">
            <el-form-item label="用户名:" prop="userName">
              <el-input clearable style="width: 100%" placeholder="请输入用户名"
                        v-model="userEditForm.userName"/>
              <div class="input_remark">用户默认密码：888888</div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="5">
          <el-col :span="10">
            <el-form-item label="角色:" prop="roleIds">
              <el-select multiple clearable v-model="userEditForm.roleIds" name="roleIds"
                         prop="roleIds">
                <el-option v-for="item in roleSelectData" :key="item.value" :value="item.value"
                           :label="item.label"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="5">
          <el-col :span="22">
            <el-form-item label="姓名:" prop="name">
              <el-input clearable style="width: 100%" placeholder="请输入姓名"
                        v-model="userEditForm.name"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="5">
          <el-col :span="22">
            <el-form-item label="手机:" prop="phone">
              <el-input clearable style="width: 100%" placeholder="请输入手机"
                        v-model="userEditForm.phone"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="5">
          <el-col :span="22">
            <el-form-item label="性别:" prop="sex">
              <el-radio v-model="userEditForm.sex" :label="1">男</el-radio>
              <el-radio v-model="userEditForm.sex" :label="2">女</el-radio>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="5">
          <el-col :span="22">
            <el-form-item label="备注:" prop="remark">
              <el-input type="textarea" clearable style="width: 100%" placeholder="请输入备注"
                        v-model="userEditForm.remark"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <toolbar style="text-align: center;margin: 0" @on-save="saveUserHandler" :privileges="btnPrivileges"
               :keys="['save']"/>
    </el-dialog>
  </div>
</template>

<script>
import paginatable from '@/components/paginatable'
import toolbar from '@/components/toolbar'
import * as userApi from '@/api/sys/user'
import * as menuApi from '@/api/sys/menu'

export default {
  name: 'user',
  data() {
    return {
      roleSelectData: [],
      showEditDialog: false,
      formLoading: false,
      userSearchForm: {
        userName: '',
        name: '',
        phone: '',
      },
      userEditForm: {
        id: '',
        userName: '',
        password: '',
        name: '',
        phone: '',
        sex: 1,
        isShow: '',
        status: '',
        isAdmin: 0,
        remark: '',
        roleIds: []
      },
      editFromRules: {
        userName: [{required: true, message: '请填写用户名', trigger: 'change'}],
        phone: [{required: true, validator: this.validator.validatePhone, message: '请填写手机号', trigger: 'change'}],
        name: [{required: true, message: '请填写姓名', trigger: 'change'}],
        roleIds: [{required: true, message: '请选择角色', trigger: 'change'}]
      },
      userTblOpts: {
        fitCols: true, loading: false,
        cols: [
          {
            prop: 'userName',
            label: '用户名'
          },
          {
            label: '状态',
            type: 'cus',
            prop: 'status',
            cellFormatter: row => {
              if (row.status === 1) {
                return '<span style="color: green">激活</span>'
              } else {
                return '<span style="color: red">冻结</span>'
              }
            }
          },
          {
            prop: 'name',
            label: '姓名'
          },
          {
            prop: 'phone',
            label: '手机'
          },
          {
            prop: 'sex',
            label: '性别',
            formatter: row => {
              if (row.sex === 1) {
                return '男'
              } else if (row.sex === 2) {
                return '女'
              }
            }
          },
          {
            prop: 'isAdmin',
            label: '是否管理员',
            formatter: row => {
              if (row.isAdmin === 0) {
                return '否'
              } else if (row.isAdmin === 1) {
                return '是'
              }
            }
          },
          {
            prop: 'remark',
            label: '备注'
          },
        ],
        data: [],
        selection: []
      },
      btnPrivileges: [],
      searchUserConditions: []
    }
  },
  components: {
    paginatable,
    toolbar
  },
  methods: {
    getRoleSelectDataHandler() {
      userApi.getRoleSelectData().then(res => {
        this.roleSelectData = res.data
      })
    },
    dialogOpenHandler() {
      this.$nextTick(() => {
        this.clearEdit()
      })
    },
    resetUserHandler() {
      this.$refs.userSearchForm.resetFields()
      this.searchUserHandler()
    },
    clearEdit() {
      if (this.$refs.userEditForm) {
        this.$refs.userEditForm.resetFields()
      }
    },
    backHandler() {
      this.formLoading = false
      this.showEditDialog = false
      this.searchUserHandler()
    },
    async saveUserHandler() {
      let valid = await this.$refs.userEditForm.validate()
      if (valid) {
        this.formLoading = true
        userApi.save(this.userEditForm).then(resp => {
          this.formLoading = true
          this.$message.success('保存成功')
          this.backHandler()
        }).catch(resp => {
          this.formLoading = false
        })
      } else {
        this.$message.warning('请按要求填写')
      }
    },
    delUserHandler(row) {
      this.$confirm('确定要删除这条记录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        userApi.del(row.id).then(resp => {
          this.searchUserHandler()
          this.$message.success('删除成功')
        })
      }).catch(() => {
      })
    },
    addUserHandler() {
      this.showEditDialog = true
    },
    editUserHandler(row) {
      this.showEditDialog = true
      userApi.load(row.id).then(resp => {
        this.userEditForm = resp.data
      })
    },
    searchUserHandler() {
      this.searchUserConditions = []
      if (this.userSearchForm.userName) {
        let val = this.userSearchForm.userName
        this.searchUserConditions.push({
          field: 'userName',
          operator: 'like',
          values: val instanceof Array ? [...val] : [val]
        })
      }

      if (this.userSearchForm.name) {
        let val = this.userSearchForm.name
        this.searchUserConditions.push({
          field: 'name',
          operator: 'like',
          values: val instanceof Array ? [...val] : [val]
        })
      }
      if (this.userSearchForm.phone) {
        let val = this.userSearchForm.phone
        this.searchUserConditions.push({
          field: 'phone',
          operator: 'like',
          values: val instanceof Array ? [...val] : [val]
        })
      }

      this.paginationUserHandler(this.userTblOpts.pageNo)
    },
    paginationUserHandler(pageNo) {
      this.$set(this.userTblOpts, 'pageNo', pageNo || 1)
      this.userTblOpts.loading = true
      userApi.pagination(this.userTblOpts, this.searchUserConditions).then(resp => {
        this.userTblOpts.data = resp.data.records
        Object.assign(this.userTblOpts, {total: Number(resp.data.total)})
        this.userTblOpts.loading = false
      })
    }
  },
  mounted() {
    this.searchUserHandler()
    this.getRoleSelectDataHandler()
    let menuId = this.$route.meta.id
    menuApi.getMenuBtn(menuId).then(resp => {
      this.btnPrivileges = resp.data
    })
  }
}
</script>
